const express = require("express");
const router = express.Router();
const path = require("path");
const fs = require("fs");
const multer = require("multer");
const upload = multer({ dest: "tmp_uploads/" });
const upload_config = require("config").get("upload_config");

router.post("/", upload.single("file"), (req, res, next) => {
  const ext = /.*\.([a-z]+)/.exec(req.file.originalname)[1];
  const targetPath = req.file.path + "." + ext;
  fs.rename(
    path.join(process.cwd(), `/${req.file.path}`),
    path.join(process.cwd(), targetPath),
    function (err) {
      if (err) return sendResult(400, null, "文件上传失败");
      res.sendResult(
        200,
        {
          tmp_path: targetPath,
          url: upload_config.get("baseURL") + "/" + targetPath,
        },
        "上传成功"
      );
    }
  );
});

module.exports = router;
